package com.jhp.eureka.balancer;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

//@controller @Service @Configuration @Component
@Component   //通用注解，将该类对象交给spring上下文管理
public class LoadBalancer {
    //轮询模式
    //定义一个计数器，初始0
    private AtomicInteger counter = new AtomicInteger(0);

    //随机模式
    /**
     * 轮询模式
     * @param instances
     * @return
     */
    public ServiceInstance getInstanceByCycle(List<ServiceInstance> instances){
        int index = counter.incrementAndGet() % instances.size();
        return instances.get(index);
    }

    /**
     * 随机模式
     * @param instances
     * @return
     */
    public ServiceInstance getInstanceByRandom(List<ServiceInstance> instances){
        int index = new Random().nextInt(instances.size());
        return instances.get(index);
    }

    //权重路由
}
